﻿using EzDesk.DesktopClient.Command;
using EzDesk.DesktopClient.Event;
using EzDesk.DesktopClient.Model;
using EzDesk.DesktopClient.MVVMEnhance;
using EzDesk.DesktopClient.UtilityView.ViewContract;
using EzDesk.Generic;
using Microsoft.Practices.Unity;

namespace EzDesk.DesktopClient.UtilityView.ViewModel
{
    public interface IUpdateItemViewModel : IFeedItemViewModel<IUpdateItemView>
    {
        DelegateCommand DisableFeedCommand { get; }
        DelegateCommand SetFeedReadCommand { get; }

        /// <summary>
        /// Returns the user-friendly name of this object.
        /// Child classes can set this property to a new value,
        /// or override it to determine the value on-demand.
        /// </summary>
        string DisplayName { get; }
    }

    public class UpdateItemViewModel : 
        FeedItemViewModel<IUpdateItemView, IUpdateItemViewModel>, 
        IUpdateItemViewModel
    {
        [InjectionConstructor]
        public UpdateItemViewModel(IUpdateItemView view)
        {
            View = view;
            InitLocalEvent();
            RaisePropertyChanged("IsRead");
        }

        public new UpdateItemViewModel SetModel(Feed feed)
        {
            base.SetModel(feed);
            return this;
        }

        public DelegateCommand DisableFeedCommand
        {
            get;
            private set;
        }

        public DelegateCommand SetFeedReadCommand { get; private set; }

        
        private void InitLocalEvent()
        {
            DisableFeedCommand = new DelegateCommand(OnDisableFeed);
            SetFeedReadCommand = new DelegateCommand(OnSetFeedRead);

            View.OnNavigate += OnNavigate;
        }

        private void OnDisableFeed()
        {
            this.IsAvailable = false;
            OnFeedStatusChanged();
        }
        private void OnSetFeedRead()
        {
            IsRead = true;
            OnFeedStatusChanged();
        }

        private void OnNavigate(object sender, GenericEventArg<string> e)
        {
            FunctionNavigateEvent.Instance.Publish(new FunctionNavigateArgs { Url = e.Value });
            this.IsRead = true;
            OnFeedStatusChanged();
        }

        private void OnFeedStatusChanged()
        {
            FeedStatusChangeEvent.Instance.Publish(FeedModel);
        }

        protected override void OnDispose()
        {
            DisableFeedCommand = null;
            View.OnNavigate -= OnNavigate;
            base.OnDispose();
        }
    }
}
